package lj.fx.tool.base;

import cn.hutool.core.util.ObjectUtil;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import lj.fx.tool.ToolFxml;
import lj.fx.tool.ToolStage;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: liuwenju
 * @date: 2023/6/26 10:14
 * @version: 1.0
 */
public class FactoryCtl {

    private final static Map<String, BaseCtl> CTL_MAP = new HashMap<>();

    public static <T extends BaseCtl> T loadCtl(String path) {
        try {
            BaseCtl baseCtl = CTL_MAP.get(path);
            if (ObjectUtil.isNull(baseCtl)) {
                CTL_MAP.put(path, baseCtl = buildCtl(ToolFxml.load(path)));
            }
            return (T) baseCtl;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T extends BaseCtl> T loadChildrenCtl(String path, ToolStage toolStage) {
        BaseCtl baseCtl = loadCtl(path);
        toolStage.setScene(baseCtl.scene);
        return (T) baseCtl;
    }

    private static BaseCtl buildCtl(FXMLLoader load) throws IOException {
        Parent parent = load.load();
        BaseCtl baseCtl = load.getController();
        baseCtl.parent = parent;
        baseCtl.load = load;
        baseCtl.scene = new Scene(parent);
        return baseCtl;
    }
}
